package com.plum.admin.common.util;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.plum.admin.common.exception.BaseException;
import com.plum.admin.common.vo.Weather;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * TODO
 *
 * @author 子丶沫
 * @version 1.0
 * @date 2021/10/13 15:39
 */
@Component
public class WeatherUtil {
    @Value("${plum.map.key}")
    private String key;
    public Map<String, String> getLocation(){
        Map<String, String> data = new HashMap(16);
        String url="https://restapi.amap.com/v3/ip?key="+key;
        String result = HttpUtil.get(url);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if(jsonObject.getInteger("status")==1){
            data.put("cityName",jsonObject.getString("province")+"-"+jsonObject.getString("city"));
            data.put("code",jsonObject.getString("adcode"));
            return data;
        }
        throw new BaseException(jsonObject.getString("info"));
    }
    public Weather getWeatherInfo(){
        Weather weather=null;
        String url="https://restapi.amap.com/v3/weather/weatherInfo?key="+key;
        Map<String, String> map = getLocation();
        String adCode = map.get("code");
        StringBuilder sb=new StringBuilder(url);
        sb.append("&city=").append(adCode)
                .append("&extensions=base");
        String result = HttpUtil.get(sb.toString());
        JSONObject object = JSONObject.parseObject(result);
        if(object.getInteger("status")==1){
            JSONArray jsonArray =JSONArray.parseArray(object.getString("lives"));
            JSONObject jsonObject = jsonArray.getJSONObject(0);
            weather=new Weather();
            weather.setProvince(jsonObject.getString("province"));
            weather.setCity(jsonObject.getString("city"));
            weather.setAdCode(jsonObject.getString("adcode"));
            weather.setWeather(jsonObject.getString("weather"));
            weather.setTemperature(jsonObject.getDouble("temperature"));
            weather.setDirection(jsonObject.getString("winddirection"));
            weather.setWindPower(jsonObject.getString("windpower"));
            return weather;
        }
        throw new BaseException(object.getString("info"));
    }
}
